// @ts-nocheck
import React, { Component } from 'react'
import { PlusOutlined } from '@ant-design/icons';
import { message, Modal, Upload } from 'antd';
import {reqDeleteImg} from '../../api/api.js'
import PropTypes from 'prop-types'

export default class PicturesWall extends Component {
  static propTypes = {
    imgs: PropTypes.array
  }
  // state = {
  //   previewVisible: false,
  //   previewImage: '', // 大图
  //   fileList: [
  //     {
  //       uid: '-1',
  //       name: 'image.png',
  //       status: 'done', // 状态：已经上传图片  uploading done err removed
  //       url: 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png',
  //     },
  //   ]
  // }

  constructor (props) {
    super (props)

    let fileList = []

    const {imgs} = this.props
    if (imgs && imgs.length>0) {
      fileList = imgs.map ((img)=> ({
        uid: img,
        name: img,
        status: 'done', // 状态：已经上传图片  uploading done err removed
        url: 'http://47.102.40.110:5000/upload/'+img
      }))
    }
    this.state = {
      previewVisible: false,
      previewImage: '', // 大图
      fileList: fileList
    }
  }

  getBase64 = (file) =>
    new Promise((resolve, reject) => {
      const reader = new FileReader();
      reader.readAsDataURL(file);

      reader.onload = () => resolve(reader.result);

      reader.onerror = (error) => reject(error);
  });

  handleCancel = () => {
    this.setState ({previewVisible: false})
  }

  handlePreview = async (file) => {
    if (!file.url && !file.preview) {
      file.preview = await this.getBase64(file.originFileObj);
    }
    this.setState ({
      previewImage: file.url || file.preview,
      previewVisible: true,
      previewTitle: file.name || file.url.substring(file.url.lastIndexOf('/') + 1)
    })
  };

  /*
  file:当前操作的图片文件
  fileList: 所有已上传图片数组
  */
  handleChange = async ({file, fileList}) => {
    console.log ('handleChange()', file.status, fileList.length, file)
    // 一旦上传成功，修正file的信息：name值 和增加url属性
    if (file.status === 'done') {
      const result = file.response // {status:   , data: {name:   , url:   }}
      console.log (result)
      if (result.status ===0) {
        message.success ('上传图片成功')
        const {name} = result.data 
        // file = fileList[fileList.length-1]  // 两个指向的不是同一个对象
        file.name = name
        file.url = 'http://47.102.40.110:5000/upload/'+name
      } else {
        message.error ('上传图片失败')
      }
    } 
    // else if (file.status === 'removed') {
    //   const result = (await reqDeleteImg(file.name)).data
    //   if (result.status === 0) {
    //     message.success ('删除图片成功')
    //   } else {
    //     message.error ('删除图片失败')
    //   }
    // }
    this.setState ({ fileList});
  }
  handleRemove = async (e) => {
    console.log ('handleRemove()',  e)
    const result = await reqDeleteImg(e.name)
    if (result.status === 0) {
      // 更新删除后的fileList
      let deleteUid = e.uid
      let newFileList = this.state.fileList.filter (i => !deleteUid.includes(i.uid))
      this.setState ({fileList: newFileList})
      message.success ('删除图片成功')
    } else {
      message.error ('删除图片失败')
    }
  }

  // 获取所有已上传图片文件名的数组 传递给父组件使用
  getImgs = () => {
    return this.state.fileList.map (file => file.name)
  }

  render() {

    const uploadButton = (
      <div>
        <PlusOutlined />
        <div
          style={{
            marginTop: 8,
          }}
        >
          Upload
        </div>
      </div>
    );

    return (
      <div>
        <Upload
        action="http://47.102.40.110:5000/manage/img/upload"
        accept='image/*'
        name='image' // 请求参数名
        listType="picture-card"
        fileList={this.state.fileList} // 已上传图片数组
        onPreview={this.handlePreview} // 显示指定大图
        onChange={this.handleChange}
        onRemove={this.handleRemove}
      >
        {this.state.fileList.length >= 8 ? null : uploadButton}
      </Upload>
      <Modal visible={this.state.previewVisible}  footer={null} onCancel={this.handleCancel}>
        <img
          alt="example"
          style={{
            width: '100%',
          }}
          src={this.state.previewImage}
        />
      </Modal>
      </div>
    )
  }
}
